package com.settlement.system.common.util.common;

import jakarta.servlet.http.HttpServletRequest;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.*;

/**
 * @author author
 */
public class NetUtil {
    /**
     * 获取本机IP
     * @return
     */
    public static Set<String> getLocalIpList() {
        Set<String> set = new TreeSet<>();
        String ip = "";
        try {
            Enumeration<?> e1 = NetworkInterface.getNetworkInterfaces();
            while (e1.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) e1.nextElement();
                Enumeration<?> e2 = ni.getInetAddresses();
                while (e2.hasMoreElements()) {
                    InetAddress ia = (InetAddress) e2.nextElement();
                    if (ia instanceof Inet6Address) {
                        continue;
                    }
                    ip = ia.getHostAddress();
                    set.add(ip);
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        set.add("0:0:0:0:0:0:0:1");
        return set;
    }

    private static final String[] HEADERS_TO_TRY = {
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "HTTP_VIA",
            "REMOTE_ADDR",
            "X-Real-IP"};

    /***
     * 获取客户端ip地址(可以穿透代理)
     * @param request
     * @return
     */
    public static String getClientIpAddress(HttpServletRequest request) {
        final String unknownString = "unknown";
        final String localIp = "0:0:0:0:0:0:0:1";
        String ip = null;
        for (String header : HEADERS_TO_TRY) {
            ip = request.getHeader(header);
            if (ip != null && ip.length() != 0 && !unknownString.equalsIgnoreCase(ip)) {
                break;
            }
        }
        //如果没有代理，则获取真实ip
        if (ip == null || ip.length() == 0 || unknownString.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return localIp.equals(ip)?"127.0.0.1":ip;
    }
}
